package com.link2room.quintesson.taobaoController;

import com.link2room.quintesson.dto.param.third.TaobaoThirdParamDto;
import com.link2room.quintesson.facade.ITaobaoReservationUpdateFacadeService;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by sss on 2017/5/3.
 */
@RestController
@RequestMapping("/taobao/Invoices")
public class TaobaoReservationUpdateController {
    @Resource
    private ITaobaoReservationUpdateFacadeService taobaoReservationUpdateFacadeService;

    @RequestMapping(value = "/UpdateRQ")
    public void taobaoService(@RequestBody String body, HttpServletResponse response) throws Exception{

        TaobaoThirdParamDto taobaoThirdParamDto =new TaobaoThirdParamDto();
        taobaoThirdParamDto.setBody(body);
        String xml=this.excuteTaobaoInvoice(taobaoThirdParamDto);

        response.setContentType("text/xml;charset=utf-8");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(xml);
        response.getWriter().close();
        response.getWriter().flush();
    }

    private String excuteTaobaoInvoice(TaobaoThirdParamDto taobaoThirdParamDto)throws Exception{
        Document xml = DocumentHelper.parseText(taobaoThirdParamDto.getBody());
        Element rootElement = xml.getRootElement();
        String rootElementName=rootElement.getName();

        Document doc = DocumentHelper.createDocument();
        Element result = doc.addElement("Result");
        result.addElement("ResultCode").addText("0");
        result.addElement("Message");
        Element orderIdElement=result.addElement("OrderId");
        result.addElement("RequestID").addText(rootElement.element("RequestID").getStringValue());
        //下单请求处理
        if("UpdateRQ ".equals(rootElementName)){
            String orderId=taobaoReservationUpdateFacadeService.resolveTaobaoReservationUpdateRQ(rootElement);
            orderIdElement.addText(orderId);
        }
        return doc.asXML();
    }
}
